package org.anno.chunkdb;

import java.io.IOException;
import java.io.OutputStream;

/**
 * Visitor interface for receiving values for a specific row with a do-nothing implementation.
 */
public interface RowVisitor {

  /**
   * Called for all columns and their types, with a chance to call {@code cell.accept} to decode a
   * value of the given type from the given column index.
   */
  default void visit(int columnIndex, Metadata.Column.Type type, Host<TypedCellVisitor> cell) {
  }

  /**
   * Writes HTML table.
   */
  public static class Html implements RowVisitor {

    private static final byte[] TD = "<td>".getBytes();
    private static final byte[] ETD = "</td>".getBytes();
    private final OutputStream out;
    private final TypedCellVisitor cellVisitor = new TypedCellVisitor() {
      @Override
      public void visitString(byte[] buf, int offset, int len) {
        try {
          out.write(TD);
          out.write(buf, offset, len);
          out.write(ETD);
        } catch (IOException e) {
          throw new IllegalStateException(e);
        }
      }
    };

    public Html(OutputStream out) {
      this.out = out;
    }

    @Override
    public void visit(int columnIndex, Metadata.Column.Type type, Host<TypedCellVisitor> cell) {
      if (type == Metadata.Column.Type.STRING) {
        cell.accept(cellVisitor);
      }
    }
  }

  /**
   * Writes table as CSV according to <a href='http://tools.ietf.org/html/rfc4180'>RFC 4180</a>.
   */
  public static class Csv implements RowVisitor {

    private final OutputStream out;
    private final TypedCellVisitor cellVisitor = new TypedCellVisitor() {
      public void visitString(byte[] buf, int offset, int len) {
        try {
          if (isPlain(buf, offset, len)) {
            out.write(buf, offset, len);
          } else {
            out.write('"');
            writeDoubledQuotes(buf, offset, len);
            out.write('"');
          }
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    };

    public Csv(OutputStream out) {
      this.out = out;
    }

    @Override
    public void visit(int columnIndex, Metadata.Column.Type type, Host<TypedCellVisitor> cell) {
      if (type == Metadata.Column.Type.STRING) {
        try {
          if (columnIndex > 0) {
            out.write(',');
          }
          cell.accept(cellVisitor);
        } catch (IOException e) {
          throw new IllegalStateException(e);
        }
      }
    }

    private static boolean isPlain(byte[] buf, int offset, int len) {
      for (int i = offset + len; --i >= offset; ) {
        switch (buf[i]) {
          case '\n':
          case '\r':
          case ',':
          case '"':
            return false;
        }
      }
      return true;
    }

    private void writeDoubledQuotes(byte[] buf, int offset, int len) throws IOException {
      int end = offset + len;
      int i = offset;
      while (i < end) {
        if (buf[i++] == '"') {
          out.write(buf, offset, i - offset);
          out.write('"');
          offset = i;
        }
      }
      if (offset < i) {
        out.write(buf, offset, i - offset);
      }
    }
  }
}
